<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<meta name="viewport"
			content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<title>网络网页</title>
		<script type="text/javascript" src="./js/uni-webview.js"></script>
		<script src="./js/dexie.min.js"></script>
		<script>
			var db = new Dexie("FriendDatabase");

			function open(scheme) {
				console.log('define:', scheme);
				db.version(1).stores(JSON.parse(scheme));
			}

			function bulkPut(key, objects) {
				console.log('bulkPut was triggered:', key, objects);
				db.table(key).bulkPut(JSON.parse(objects)).catch(err => {
					console.log(JSON.stringify(err))
				});
			}

			function putFile(tableKey, fileKey, filePath) {
				console.log('putFile was triggered:', filePath);
				plus.io.resolveLocalFileSystemURL(filePath, function(entry) {
					entry.file(function(file) {
						console.log('resolveLocalFile:' + file.name, file.type, file.size);

						var reader = new plus.io.FileReader();
						reader.readAsDataURL(file);
						reader.onloadend = function() {
							var base64String = reader.result;
							console.log('resolveLocalFileBase64:', base64String, base64String.length);

							// var arr = base64String.split(','),
							// 	mime = arr[0].match(/:(.*?);/)[1],
							// 	bstr = atob(arr[1]),
							// 	n = bstr.length,
							// 	u8arr = new Uint8Array(n);
							// while (n--) {
							// 	u8arr[n] = bstr.charCodeAt(n);
							// }

							db.table(tableKey).put({
								key: fileKey,
								file: file,
								base64: base64String,
								// blob: new Blob([u8arr], {type: mime})
							}).catch(err => {
								console.error("Failed to putFile:" + err.message)
							})
						}
					});
				}, function(e) {
					console.log("Resolve file URL failed: " + e.message);
				});
			}

			function put(key, object) {
				console.log('put was triggered:', key, object);
				let record = JSON.parse(object);
				db.table(key).put(record).catch(err => {
					console.error("Failed to add:" + err.message)
				});
			}

			function query(key, where) {
				console.log('query where:', key, where);
				db.table(key).where(JSON.parse(where)).toArray(function(result) {
					console.log('query result:', JSON.stringify(result));
					uni.postMessage({
						data: {
							table: key,
							result: result
						}
					});
				});
			}

			function loadFile(tKey, where) {
				console.log('loadFile:', tKey, where);
				db.table(tKey).where(JSON.parse(where)).toArray(function(result) {
					console.log('loadFile result:', result[0].file.name);
					uni.postMessage({
						data: {
							table: tKey,
							result: result
						}
					});
				}).catch(err => {
					console.error("Failed to loadFile:" + err.message)
				});
			}
		</script>
	</head>
	<body>
		<p class="desc">数据加载中，请稍等片刻...</p>
	</body>
</html>